<?php
/**
 * Created by PhpStorm.
 * User: lixy
 * Date: 2015/12/24
 * Time: 13:57
 */

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\lib\WeixinUtils;
use app\lib\WeixinUser;
use app\models\weixin\T_WXMALL_SCENE_USER;
use app\models\weixin\T_WXMALL_USER;
use app\models\ActivityDao;
use app\models\FxDao;
use yii\helpers\Url;
class WeixinController extends Controller
{
    public $enableCsrfValidation = false;
    public $layout="@app/views/webapp_layouts/main";
//公众号回调
    public function actionIndex()
    {
       if(!empty($_GET["echostr"])) {
           $echoStr = $_GET["echostr"];
           if (WeixinUtils::checkSignature()) {
                //file_put_contents("d:/111.txt",$echoStr);
               echo $echoStr;
               exit;
           }
       }else{

           $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//           Yii::trace($postStr);

           $echoStr="";
          $msg= simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
           $user_openid=(string)$msg->FromUserName;

           $weixinUser=new WeixinUser();
           $weixinUser->FromUserName=(string)$msg->ToUserName;
           $weixinUser->ToUserName=$user_openid;

//           Yii::trace($msg);
           if($msg->MsgType=="text") {
               if ($msg->Content=="1") {
                   $echoStr = WeixinUtils::_response_text($weixinUser, "我的分销 http://wx.duolahe.com/biz_weixin/web/index-test.php/wx-fx/my-fx");
               }
               if ($msg->Content=="2") {
                   $echoStr = WeixinUtils::_response_text($weixinUser, "我的送礼记录 http://wx.duolahe.com/biz_weixin/web/index-test.php/wx-home/send-record");
               }
               if ($msg->Content=="3") {
                   $echoStr = WeixinUtils::_response_text($weixinUser, "我收到的礼物 http://wx.duolahe.com/biz_weixin/web/index-test.php/wx-home/receive-record");
               }
               if ($msg->Content=="4") {
                   $echoStr = WeixinUtils::_response_text($weixinUser, "兑换朵拉卡 http://wx.duolahe.com/biz_weixin/web/index-test.php/wx-home/voucher-exchange-user");
               }

               if ($msg->Content=="5") {
                   $echoStr = WeixinUtils::_response_text($weixinUser, "龙珠专区 http://wx.duolahe.com/biz_weixin/web/index-test.php/special/dragon-ball");
               }
               if ($msg->Content=="6") {
                  $echoStr = WeixinUtils::_response_text($weixinUser, "新春礼包 http://wx.duolahe.com/biz_weixin/web/index-test.php/wx-bag/home");
               }
               if ($msg->Content=="7") {
                  $echoStr = WeixinUtils::_response_text($weixinUser, "我的朵拉币 http://wx.duolahe.com/biz_weixin/web/index-test.php/wx-home/doracoin-record");
               }
               if ($msg->Content=="99") {
                  $echoStr = $this->bigbangMsg($weixinUser);
               }

               if ($msg->Content=="马化腾") {
                   $echoStr = WeixinUtils::_response_text($weixinUser, Url::to(['wx-game/game1'],true));
               }
               if ($msg->Content=="颜值" || $msg->Content=="测颜值") {
                   $echoStr = WeixinUtils::_response_text($weixinUser, '<a href=\'http://e.msxiaobing.com/webapps/imagegame?p=IwAQAF8AEAB5ABEAeQAxAAYAUwBKAAEAEgA0ADMAMQBhADYACQBjAHMAeQBhAG4AegBoAGkA\'>点这里</a>');
               }
               if ($msg->Content=="龙珠") {


                   $item=(object)null;
                   $item->title="龙珠唤神龙，你可以实现一个愿望？";
                   $item->description="集齐龙珠唤神龙，神秘大奖向你招手中！";
                   $item->picurl="https://mmbiz.qlogo.cn/mmbiz/x40YPDNaO4vVtT6bQI2eIwUujrWUicJ6OepeNfEbqSEqAUf7PvyM3iapXNqB44YVk0Gy8yt7zPRcpKIou8ExN1xg/0?wx_fmt=jpeg";
                   $item->url="http://wx.duolahe.com/biz_weixin/web/index.php/special/dragon-ball";


                   $content=[WeixinUtils::_news_Article($item),];
                   $echoStr =( WeixinUtils::_response_news($weixinUser,$content));

               }
               if ($msg->Content=="test") {

					
                   $item=(object)null;
                   $item->title="您拥有了打折权限";
                   $item->description="拉盒将不定期开展新老用户开启魔盒好礼活动，你将在开启魔盒的同时，香到意外魔力种子！";
                   $item->picurl="http://mmbiz.qpic.cn/mmbiz/x40YPDNaO4tUpwG54LdamgINF8sVSdbPhJ004nI3A0cZdicPeqibmeng3bffRJxCLyQC8BVjrWc6ibAicbIUXeQEFA/0?wx_fmt=jpeg";
                   $item->url="http://u.liveapp.cn/804841";

                   
                   $content=[WeixinUtils::_news_Article($item),];
                   $echoStr =( WeixinUtils::_response_news($weixinUser,$content));

               }

//                   Yii::trace($echoStr);
               echo $echoStr;
               exit;
           }

            if($msg->MsgType=="event") {
				$echoStr ="";
                //关注公众号
                if($msg->Event=='subscribe'){
                    $openid=$weixinUser->ToUserName;
                    $re=T_WXMALL_USER::getUserIdByOpenId($openid);
                    //判断用户表是否有
                    if($re==false){
                        //添加用户
                       $userinfo= WeixinUtils::get_weixin_userinfo_base($openid);
                        $datas['WX_OPENID']=$openid;
                        $datas['NICK_NAME']=$userinfo->nickname;
                        $datas['HEADER_URL']=$userinfo->headimgurl;
                        $userid=T_WXMALL_USER::addUser($datas);

                    } else{
                          $userid=$re;
                    }

                   $EventKey= $msg->EventKey;
                    if($EventKey!='' && substr($EventKey, 0,8)=='qrscene_') {///偶尔会发出last_trade_no234234234
                        //qrscene_
                        $EventKey = substr($EventKey, 8);
//                        echo  WeixinUtils::_response_text($weixinUser,$EventKey.'=='.$userid);
//                        exit;
                        //尝试添加分销的下线用户 $EventKey $userid
                        $re=FxDao::P_WXMALL_USER_INVITE($EventKey, $userid);

                        if($re=='1'){
                           echo static::get_FxHello($weixinUser);
                            exit;
                        }
                        $echoStr = $this->SCENE_handle($weixinUser,$EventKey,'subscribe');
                        if($echoStr==''){
                            $echoStr= self::subscribe_msg($weixinUser);
                        }
                        echo $echoStr;
                        exit;
                    }else{
                        if (YII_ENV=='dev') {
                            echo self::subscribe_msg($weixinUser);
                            exit;
                        }

                        try {
                            //添加分销的下线用户 $EventKey $userid
                            FxDao::P_WXMALL_USER_INVITE('', $userid);
                        }catch(\Exception $e){
                            $echoStr = WeixinUtils::_response_text($weixinUser,$e->getMessage());
                            echo $echoStr;
                            exit;
                        }
                    }

					 echo self::subscribe_msg($weixinUser);
                    exit;
                }
                if($msg->Event=='SCAN'){
                    $EventKey=$msg->EventKey;

                    //处理活动
                    $echoStr = $this->SCENE_handle($weixinUser,$EventKey,'SCAN');
                    echo $echoStr;
                    exit;
                }
                if($msg->Event=='CLICK'){
                    $EventKey=$msg->EventKey;
                    if($EventKey=='400'){
                        $echoStr = WeixinUtils::_response_text($weixinUser, "客服热线：400-860-3111\n客服微信：doraboxgift");
                        echo $echoStr;
                        exit;
                    }
               /*     {
                        "type" : "click",
					"name" : "客服热线",
					"key" : "400",
					"sub_button" : []
				}*/


                }
            }

       }

    }

    //活动场景扫描
    public function SCENE_handle($weixinUser,$EventKey,$type){


        $openid=$weixinUser->ToUserName;
        //判断用户表是否有
        $re=T_WXMALL_USER::getUserIdByOpenId($openid);
        if($re==false){
            $echoStr =( WeixinUtils::_response_text($weixinUser,'活动场景扫描:用户信息不存在'));
            return $echoStr;
        }else{
            $userid=$re;
        }
        $echoStr="";
        if (YII_ENV=='dev') {
            //调试用
            //尝试添加分销的下线用户 $EventKey $userid
            try {
                if( FxDao::P_WXMALL_USER_INVITE($EventKey, $userid)=='1'){
                   echo  self::send_FxHello($weixinUser);
                    exit;
                }
            } catch (\Exception $e) {

                return ( WeixinUtils::_response_text($weixinUser,$e->getMessage()));
                exit();
            }



            $echoStr =( WeixinUtils::_response_text($weixinUser,'type:'.$type.';key:'.$EventKey.';user_id:'.$userid));
            return $echoStr;
        }
        /*//场景处理
        if($EventKey=='1'){//2016-1-15活动
            //$echoStr = WeixinUtils::_response_text($weixinUser,$msg->asXML());
            //记录场景值
            T_WXMALL_SCENE_USER::setSCENE_USER($weixinUser->ToUserName,(string)$EventKey,1,1);
			//图文消息
			$item=(object)null;
		   $item->title="【哇哇哇】朵拉送你的50元红包已经到账！";
		   $item->description="朵拉发放红包了，扫描立刻领取！";
		   $item->picurl="http://mmbiz.qpic.cn/mmbiz/x40YPDNaO4vMXGmbkHgde5Z0g3VLuxNhLZlh9NplQpMK9twMwYuKpgzZeiaRRwvUyiayL7DTDfFAIlGuy6G0ibwZg/0?wx_fmt=jpeg";
		   $item->url="http://mp.weixin.qq.com/s?__biz=MzI3MDEyNjc5Nw==&mid=402673753&idx=1&sn=fb345b98521ee05b6f38a3e7803ed53c#rd";

		   
		   $content=[WeixinUtils::_news_Article($item),];
		   $echoStr =( WeixinUtils::_response_news($weixinUser,$content));
			
			
			
        }
        if($EventKey=='2') {//2016-1-22活动

            //产生送礼记录

            $re=ActivityDao::P_WXMAL_ACTIVITY("2",$userid);
            if($re=='1'){
                //图文消息
                $item=(object)null;
                $item->title="【恭喜】朵拉送的168元［有钱有闲疯女人专享卡］已经到账";
                $item->description="有钱、有闲、任性的美少妇还有社交化礼赠需求！！";
                $item->picurl="https://mmbiz.qlogo.cn/mmbiz/x40YPDNaO4uIroEiaYfGOfLAuwTTicP42UtIsQFBvPvosQEHLDRDtib241qDVoAFbDRuUO3oXhQSQibZyibfkuH13xQ/0?wx_fmt=jpeg";
                $item->url="http://mp.weixin.qq.com/s?__biz=MzI3MDEyNjc5Nw==&mid=403179763&idx=1&sn=15891a332699d2e8202f020d78a17121#rd";

                $echoStr =( WeixinUtils::_response_text($weixinUser,$content));
            }else{
                //错误输出
                $echoStr =( WeixinUtils::_response_text($weixinUser,$re));
            }

        }*/
      return $echoStr;
    }
    //卡券兑换
    public function actionExchange(){

    }
    public  function  get_FxHello($weixinUser){
        return $this->bigbangMsg_fx($weixinUser);
        $count=T_WXMALL_USER::getUserCount()+111257;
        return WeixinUtils::_response_text($weixinUser,"欢迎加入朵拉盒，您是{$count}个朵拉伙伴！");
     }
    //网页回调
    public function actionGetUserInfo(){

       $userinfo= WeixinUtils::weixin_userinfo_filter();
        var_dump($userinfo );
        echo "<img src='$userinfo->headimgurl' />";

    }
//http://wxdev.duolahe.com/biz_weixin/web/index.php/weixin/qr?key=1&type=2
    public function actionQr($key,$type){
        if($type=='1') {
            $t=WeixinUtils::qrcode_temp($key);
        }
        if($type=='2') {
            $t=WeixinUtils::qrcode_forever($key);
        }
        var_dump($t);
//        $t->ticket
        $t=urlencode($t->ticket);
        echo "<br/>https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$t}";
    }
    private function subscribe_msg($weixinUser){
        return $this->Msg20160803($weixinUser);
        $baseurl=Url::to(["/"],true);
//<a href='$baseurl/wx-home/home'>
        $tmp="/爱心 人家等你好久了，感谢关注朵拉哦！"
            ."\n"
            ."\n/调皮 朵拉一键玩转送礼新境界！"
            ."\n/坏笑 一键<a href='$baseurl/wx-home/home'>送礼包</a>请戳这儿~ "
            ."\n/礼物 祝福<a href='$baseurl/wx-biz/card-list'>送礼卡</a>快速入口~ "
            ."\n/示爱 节庆<a href='$baseurl/special/dragon-card'>端午礼卡</a>隆重推新~ "
            ."\n/微笑 <a href='$baseurl/wx-home/voucher-exchange-user'>礼卡兑换</a>请戳这儿~ "
            ."\n"
            ."\n/微笑 <a href='http://mp.weixin.qq.com/s?__biz=MzI3MDEyNjc5Nw==&mid=504653442&idx=2&sn=b75888d694f407811dda8fe77c6b7119&scene=0&previewkey=oB09Fa0bqgBa5TisFPdWicNS9bJajjJKzz%2F0By7ITJA%3D#wechat_redirect'>分享赚钱</a> "
            ."\n"
            ."\n/微笑 戳  <a href='http://mp.weixin.qq.com/s?__biz=MzI3MDEyNjc5Nw==&mid=504653747&idx=2&sn=7f6563cea4bc6afd27cb6306d2a43064&scene=0&previewkey=VGXFsYW3JBf84wl%2FI1NRtcwqSljwj2bfCUaCyDofEow%3D#wechat_redirect'>福利</a>  有惊喜！"
            ."\n"
            ."\n朵拉盒超越你的想像！ "
            ."\n我是互联网礼赠服务专家！ "
            ."\n"
            ."\n朵拉盒密电：400-860-3111 ";
        return WeixinUtils::_response_text($weixinUser,$tmp);
    }
    private function Msg20160803($weixinUser){
        $tmp="\n欢迎关注朵拉盒，终于等到你，么么哒 /调皮"
            ."\n"
            ."\n朵拉盒致力于帮助企业打造雇主品牌形象，为企业提供弹性福利平台、定制化福利方案设计、多样化福利产品选择等 /示爱"
            ."\n"
            ."\n专注于员工福利综合服务平台，员工福利领域，提供专业的员工福利整体外包解决方案 /微笑"
            ."\n"
            ."\n中秋将至，朵拉盒将携手众多优质供应商，推出朵拉卡和专享服务，呈献给大家 (@^o^@) ";
        return WeixinUtils::_response_text($weixinUser,$tmp);
    }
    private function bigbangMsg($weixinUser){
        $item=(object)null;
        $item->title="免费送你Bigbang三巡重庆站门票！错过再等7年！ ";
        $item->description="地球人都知道，2016年3月，在数百万名歌迷期待下，韩国最受欢迎的组合BIGBANG 终于来中国开演唱会了！！";
        $item->picurl="https://mmbiz.qlogo.cn/mmbiz/x40YPDNaO4vdwiaic1pBhRqNxKmEJmfczNBvTAPKXolVuvHhzhszERCeXDtJN9UEpfjE99UwOqGWqNPCJkp4hCOw/0?wx_fmt=jpeg";
        $item->url="http://mp.weixin.qq.com/s?__biz=MzI3MDEyNjc5Nw==&mid=2652137438&idx=1&sn=cfef0b6322e4973eb412db62415b44bb&scene=0";


        $content=[WeixinUtils::_news_Article($item),];
        return ( WeixinUtils::_response_news($weixinUser,$content));
    }
    private function bigbangMsg_fx($weixinUser){
        $item=(object)null;
        $item->title="免费送你Bigbang三巡重庆站门票！错过再等7年！.. ";
        $item->description="地球人都知道，2016年3月，在数百万名歌迷期待下，韩国最受欢迎的组合BIGBANG 终于来中国开演唱会了！！";
        $item->picurl="https://mmbiz.qlogo.cn/mmbiz/x40YPDNaO4vdwiaic1pBhRqNxKmEJmfczNBvTAPKXolVuvHhzhszERCeXDtJN9UEpfjE99UwOqGWqNPCJkp4hCOw/0?wx_fmt=jpeg";
        $item->url="http://mp.weixin.qq.com/s?__biz=MzI3MDEyNjc5Nw==&mid=2652137438&idx=1&sn=cfef0b6322e4973eb412db62415b44bb&scene=0";


        $content=[WeixinUtils::_news_Article($item),];
        return ( WeixinUtils::_response_news($weixinUser,$content));
    }

    /**
     * get-wx-token-handle
     */
    public function actionGetWxTokenHandle(){
        $access_token=WeixinUtils::get_weixin_token_memcache();
        return self::renderJson($access_token);

    }
    public static function renderJson($data = null, $status = 0, $message = 'success')
    {
        $result = [
            'status' => $status,
            'message' => $message,
            'data' => $data
        ];

        return json_encode($result, true);
    }
}